package com.wy.supermarket.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wy.supermarket.entity.Goods;
import com.wy.supermarket.repository.GoodsRepository;

@RestController
@RequestMapping("/goods")
public class GoodsController {
	@Autowired //自动装载
	private GoodsRepository goodsRepository;
	
	@GetMapping("/findAll/{page}/{size}")
	public Page<Goods> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
		Pageable pageable=PageRequest.of(page-1, size);
		return goodsRepository.findAll(pageable);
	}
	
	@PostMapping("/addGoods")
	public String addGoods(@RequestBody Goods goods) {
		Goods result=goodsRepository.save(goods);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@GetMapping("/findById/{gnum}")
	public Goods findById(@PathVariable("gnum") Integer gnum) {
		return goodsRepository.findById(gnum).get();
	}
	
	@GetMapping("/findByName/{gname}")
	public List<Goods> findByGnameLike(@PathVariable("gname") String gname) { //模糊查询
		return goodsRepository.findByGnameLike("%"+gname+"%");
	}
	
	@PutMapping("/updateGoods")
	public String updateGoods(@RequestBody Goods goods) {
		Goods result=goodsRepository.save(goods);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@DeleteMapping("/deleteById/{gnum}")
	public Goods deleteById(@PathVariable("gnum") Integer gnum) {
		goodsRepository.deleteById(gnum);
		return null;
	}

}

